package laravel.mvc.view.blade;

import entity_model.Attribute;
import entity_model.Entity;
import entity_model.Relationship;
import html.*;
import laravel.Laravel;
import utils.titles.Title;
import node.TextNode;

/**
 * Created by nuno-rafael-figueiredo on 04-05-2014.
 */
public class CreateBlade extends Blade{
    public CreateBlade(Laravel laravel, Entity entity) {
        super(laravel, entity, Title.fromLowerCamel("create"));

        content.appendChild(new Div()
                .addClass("row")
                .appendChild(new Div()
                        .addClass("col-lg-12")
                        .appendChild(new H1("Create " + entity.getTitle().toLowerCase()))));

        Form form = new Form();
        form.attribute("action", " {{URL::route('" + lowerUnderscoreEntityName + "-create-post') }} ");
        form.attribute("method", "post");
        form.attribute("role", "form");
        content.appendChild(form);

        for(Entity aux = entity; aux != null; aux = aux.getBaseEntity()) {
            for (Attribute member : aux.getAttributes()) {
                final Title title = member.getTitle();

                Div div = new Div();
                div.attribute("class", "form-group");
                form.appendChild(div);

                Input input = new Input();
                input.attribute("id", "input" + title.toUpperCamel());
                input.attribute("type", "text");
                input.attribute("name", title.toLowerCamel());
                input.attribute("class", "form-control");
                input.attribute("placeholder", "Enter " + title.toLowerCase());
                div.appendChild(input);

                If anIf = new If("$errors->has('" + title.toLowerCamel() + "')");
                div.appendChild(anIf);
                anIf.appendChild(new TextNode("{{ $errors->first('" + title.toLowerCamel() + "') }}"));
            }
        }

        for(Relationship.Related related : entity.getRelateds())
            form.appendChild(new Span(related.getTheOthersRole().getTitle().toCapitalized()));

        Button button = new Button("Create");
        button.attribute("type", "submit");
        button.attribute("class", "btn btn-default");
        button.attribute("value", "Create " + entity.getTitle().toUpperCamel());
        form.appendChild(button);

        content.appendChild(new TextNode("{{ Form::token() }}"));
    }
}
